/**
 * 图片上传
 */
import { ref, nextTick } from 'vue'
import { UploadCustomRequestOptions } from 'naive-ui'
import { FileTypeEnum } from '@/enums/fileTypeEnum'
import { ResultEnum } from '@/enums/httpEnum'
import { fetchRouteParamsLocation } from '@/utils'
import { uploadFile } from '@/api/path'
import { useSystemStore } from '@/store/modules/systemStore/systemStore'
const systemStore = useSystemStore()

export const useImageUpload = () => {
    const uploadFileListRef = ref()
    // 背景图片大小限制（5M）
    const backgroundImageSize = 5

    // 上传图片前置处理
    //@ts-ignore
    const beforeUploadHandle = async ({ file }) => {
        uploadFileListRef.value = []
        const type = file.file.type
        const size = file.file.size

        if (size > 1024 * 1024 * backgroundImageSize) {
            window['$message'].warning(`图片超出 ${backgroundImageSize}M 限制，请重新上传！`)
            return false
        }
        if (type !== FileTypeEnum.PNG && type !== FileTypeEnum.JPEG && type !== FileTypeEnum.GIF) {
            window['$message'].warning('文件格式不符合，请重新上传！')
            return false
        }
        return true
    }


    // 自定义上传操作
    const customRequest = (options: UploadCustomRequestOptions) => {
        return new Promise((resolve) => {
            const { file } = options
            nextTick(async () => {
                if (file.file) {
                    // 修改名称
                    const newNameFile = new File(
                        [file.file],
                        `${fetchRouteParamsLocation()}_index_background.png`,
                        { type: file.file.type }
                    )
                    let uploadParams = new FormData()
                    uploadParams.append('object', newNameFile)
                    const uploadRes = await uploadFile(uploadParams)

                    if (uploadRes && uploadRes.code === ResultEnum.SUCCESS) {
                        const url = `${systemStore.getFetchInfo.OSSUrl}${uploadRes.data.fileName
                            }?time=${new Date().getTime()}`
                        console.log('url', url)
                        resolve(url)
                    } else {
                        window['$message'].error('添加图片失败，请稍后重试！')
                        resolve('')
                    }
                } else {
                    window['$message'].error('添加图片失败，请稍后重试！')
                    resolve('')
                }
            })
        })
    }


    return {
        uploadFileListRef,
        customRequest,
        beforeUploadHandle
    }
}